﻿using Aspose.Cells;
using System.Data;

namespace NET6.WebAPI.Helpers
{
    public static class AsposeExcelHelper
    {
        /// <summary>
        /// 根据 DataTable 生成 Excel(修改文件后缀即可生成 PDF)
        /// </summary>
        /// <param name="dt">数据表对象</param>
        /// <param name="filePath">生成路径</param>
        /// <param name="titles">标题数组(可选)</param>
        public static void GenerateExcelByDataTable(DataTable dt, string filePath, string[] titles = null)
        {
            Workbook book = new Workbook();
            Worksheet sheet = book.Worksheets[0];

            int rowIndex = 0;

            if (titles != null)
            {
                // 标题行
                for (int i = 0; i < titles.Length; i++)
                {
                    sheet.Cells[rowIndex, i].PutValue(titles[i]);
                }
            }
            else
            {
                // 标题行
                foreach (DataColumn column in dt.Columns)
                {
                    sheet.Cells[rowIndex, column.Ordinal].PutValue(column.ColumnName);
                }
            }

            rowIndex++;

            // 数据行
            foreach (DataRow row in dt.Rows)
            {
                int cellIndex = 0;

                foreach (DataColumn column in dt.Columns)
                {
                    sheet.Cells[rowIndex, cellIndex++].PutValue(row[column]);
                }

                rowIndex++;
            }

            sheet.AutoFitColumns(); // 自动调整列宽 
            book.Save(filePath);
            book.Dispose();
        }
    }
}
